<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/yuwanzi.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/yuwanzi.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/yuwanzi.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/yuwanzi.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/yuwanzi.io/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"suyuhuan.gitee.io","root":"/yuwanzi.io/","images":"/yuwanzi.io/images","scheme":"Muse","version":"8.2.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Suche...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="1. Lucene介绍 Lucene是apache下的一个开源的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎（英文与德文两种西方语言）。它为软件开发人员提供一个简单易用的工具包（类库）,以方便的在目标系统中实现全文检索的功能。 全文检索 全文检索首先将要查询的目标文档中的词提取出来，组成索引，通过查询索引达到搜索目">
<meta property="og:type" content="article">
<meta property="og:title" content="使用Lucene实现全文检索">
<meta property="og:url" content="https://suyuhuan.gitee.io/yuwanzi.io/2016/06/19/2016-06-19-lucene/index.html">
<meta property="og:site_name" content="玉丸子 | Blog">
<meta property="og:description" content="1. Lucene介绍 Lucene是apache下的一个开源的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎（英文与德文两种西方语言）。它为软件开发人员提供一个简单易用的工具包（类库）,以方便的在目标系统中实现全文检索的功能。 全文检索 全文检索首先将要查询的目标文档中的词提取出来，组成索引，通过查询索引达到搜索目">
<meta property="og:locale">
<meta property="og:image" content="http://ww2.sinaimg.cn/mw690/63503acbjw1f67nt0n317j20o60l80u0.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/mw690/63503acbjw1f67nv272uaj20ag0fumxd.jpg">
<meta property="article:published_time" content="2016-06-18T16:00:00.000Z">
<meta property="article:modified_time" content="2020-11-07T00:58:17.000Z">
<meta property="article:author" content="玉丸子">
<meta property="article:tag" content="全文检索引擎">
<meta property="article:tag" content="Lucene">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://ww2.sinaimg.cn/mw690/63503acbjw1f67nt0n317j20o60l80u0.jpg">


<link rel="canonical" href="https://suyuhuan.gitee.io/yuwanzi.io/2016/06/19/2016-06-19-lucene/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh'
  };
</script>
<title>使用Lucene实现全文检索 | 玉丸子 | Blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/yuwanzi.io/atom.xml" title="玉丸子 | Blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Navigationsleiste an/ausschalten" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/yuwanzi.io/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">玉丸子 | Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Inhaltsverzeichnis
        </li>
        <li class="sidebar-nav-overview">
          Übersicht
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-Lucene%E4%BB%8B%E7%BB%8D"><span class="nav-number">1.</span> <span class="nav-text">1. Lucene介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%85%A8%E6%96%87%E6%A3%80%E7%B4%A2"><span class="nav-number">1.1.</span> <span class="nav-text">全文检索</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Lucene%E7%9A%84%E4%BC%98%E7%82%B9"><span class="nav-number">1.2.</span> <span class="nav-text">Lucene的优点</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-Lucene%E6%A3%80%E7%B4%A2%E6%B5%81%E7%A8%8B"><span class="nav-number">2.</span> <span class="nav-text">2. Lucene检索流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-%E7%B4%A2%E5%BC%95%E7%9A%84%E9%80%BB%E8%BE%91%E7%BB%93%E6%9E%84"><span class="nav-number">3.</span> <span class="nav-text">3. 索引的逻辑结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-%E5%88%9B%E5%BB%BA%E7%B4%A2%E5%BC%95"><span class="nav-number">4.</span> <span class="nav-text">4. 创建索引</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E7%B4%A2%E5%BC%95%E7%9A%84%E6%B5%81%E7%A8%8B"><span class="nav-number">4.1.</span> <span class="nav-text">创建索引的流程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E7%B4%A2%E5%BC%95"><span class="nav-number">4.2.</span> <span class="nav-text">创建索引</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-%E6%90%9C%E7%B4%A2%E7%B4%A2%E5%BC%95"><span class="nav-number">5.</span> <span class="nav-text">5. 搜索索引</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8QueryParse"><span class="nav-number">5.1.</span> <span class="nav-text">使用QueryParse</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8Query%E7%9A%84%E5%AD%90%E7%B1%BB"><span class="nav-number">5.2.</span> <span class="nav-text">使用Query的子类</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-%E5%88%A0%E9%99%A4%E7%B4%A2%E5%BC%95"><span class="nav-number">6.</span> <span class="nav-text">6. 删除索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-%E4%BF%AE%E6%94%B9%E7%B4%A2%E5%BC%95"><span class="nav-number">7.</span> <span class="nav-text">7. 修改索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#8-%E7%9B%B8%E5%85%B3%E5%BA%A6%E6%8E%92%E5%BA%8F"><span class="nav-number">8.</span> <span class="nav-text">8. 相关度排序</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%89%8B%E5%8A%A8%E8%AE%BE%E7%BD%AE%E6%9D%83%E5%80%BC"><span class="nav-number">8.1.</span> <span class="nav-text">手动设置权值</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">玉丸子</p>
  <div class="site-description" itemprop="description">这里是玉丸子的个人博客,与你一起发现更大的世界。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/yuwanzi.io/archives">
          <span class="site-state-item-count">68</span>
          <span class="site-state-item-name">Artikel</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/yuwanzi.io/categories/">
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">Kategorien</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/yuwanzi.io/tags/">
        <span class="site-state-item-count">46</span>
        <span class="site-state-item-name">schlagwörter</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2016/06/19/2016-06-19-lucene/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          使用Lucene实现全文检索
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2016-06-19 00:00:00" itemprop="dateCreated datePublished" datetime="2016-06-19T00:00:00+08:00">2016-06-19</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">后端</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/%E5%85%A8%E6%96%87%E6%A3%80%E7%B4%A2/" itemprop="url" rel="index"><span itemprop="name">全文检索</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/%E5%85%A8%E6%96%87%E6%A3%80%E7%B4%A2/Lucene/" itemprop="url" rel="index"><span itemprop="name">Lucene</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h3 id="1-Lucene介绍"><a href="#1-Lucene介绍" class="headerlink" title="1. Lucene介绍"></a>1. Lucene介绍</h3><p> Lucene是apache下的一个开源的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎（英文与德文两种西方语言）。<br>它为软件开发人员提供一个简单易用的工具包（类库）,以方便的在目标系统中实现全文检索的功能。</p>
<h4 id="全文检索"><a href="#全文检索" class="headerlink" title="全文检索"></a>全文检索</h4><p> 全文检索首先将要查询的目标文档中的词提取出来，组成索引，通过查询索引达到搜索目标文档的目的。这种先建立索引，再对索引进行搜索的过程就叫全文检索（Full-text Search）。</p>
<h4 id="Lucene的优点"><a href="#Lucene的优点" class="headerlink" title="Lucene的优点"></a>Lucene的优点</h4><ol>
<li>索引文件格式独立于应用平台。Lucene定义了一套以8位字节为基础的索引文件格式，使得兼容系统或者不同平台的应用能够共享建立的索引文件。</li>
<li>在传统全文检索引擎的倒排索引的基础上，实现了分块索引，能够针对新的文件建立小文件索引，提升索引速度。然后通过与原有索引的合并，达到优化的目的。</li>
<li>优秀的面向对象的系统架构，使得对于Lucene扩展的学习难度降低，方便扩充新功能。</li>
<li>设计了独立于语言和文件格式的文本分析接口，索引器通过接受Token流完成索引文件的创立，用户扩展新的语言和文件格式，只需要实现文本分析的接口。</li>
<li>已经默认实现了一套强大的查询引擎，用户无需自己编写代码即可使系统可获得强大的查询能力，Lucene的查询实现中默认实现了布尔操作、模糊查询（Fuzzy Search[11]）、分组查询等等。</li>
</ol>
<h3 id="2-Lucene检索流程"><a href="#2-Lucene检索流程" class="headerlink" title="2. Lucene检索流程"></a>2. Lucene检索流程</h3><p><img src="http://ww2.sinaimg.cn/mw690/63503acbjw1f67nt0n317j20o60l80u0.jpg"></p>
<ul>
<li>创建索引流程:Gather Data(采集数据) –&gt; 构造文档对象 –&gt; 分词 –&gt; 创建索引并存入索引库</li>
<li>搜索流程:用户发起搜索请求 –&gt; 创建查询对象 –&gt; 从索引库中搜索 –&gt; 渲染并返回搜索结果</li>
</ul>
<h3 id="3-索引的逻辑结构"><a href="#3-索引的逻辑结构" class="headerlink" title="3. 索引的逻辑结构"></a>3. 索引的逻辑结构</h3><ul>
<li>一个非结构化的数据统一格式为<code>document</code>文档,一个<code>document</code>可以有多个<code>field</code>。</li>
<li>当用户搜索时,Lucene会从索引域中搜索,并找到对应的<code>document</code>,将<code>document</code>中的<code>filed</code>进行分词,然后根据分词创建索引。</li>
</ul>
<h3 id="4-创建索引"><a href="#4-创建索引" class="headerlink" title="4. 创建索引"></a>4. 创建索引</h3><h4 id="创建索引的流程"><a href="#创建索引的流程" class="headerlink" title="创建索引的流程"></a>创建索引的流程</h4><p><img src="http://ww1.sinaimg.cn/mw690/63503acbjw1f67nv272uaj20ag0fumxd.jpg"></p>
<ol>
<li>IndexWriter是核心对象,它可以完成创建索引、更新索引、删除索引等操作。</li>
<li>Directory负责对索引进行存储,它是一个抽象类,子类为FSDirectory(文件中存储)、RAMDirectory(内存中存储)</li>
</ol>
<h4 id="创建索引"><a href="#创建索引" class="headerlink" title="创建索引"></a>创建索引</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">createIndex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="comment">// 获得原始数据</span></span><br><span class="line">	ItemsDao itemsDao = <span class="keyword">new</span> ItemsDaoImpl();</span><br><span class="line">	List&lt;Items&gt; items = itemsDao.findAllItems();</span><br><span class="line">	<span class="comment">// 创建Document</span></span><br><span class="line">	List&lt;Document&gt; documents = <span class="keyword">new</span> ArrayList&lt;Document&gt;();</span><br><span class="line">	Document document = <span class="keyword">null</span>;</span><br><span class="line">	<span class="comment">// 遍历原始数据并封装到field</span></span><br><span class="line">	<span class="keyword">for</span> (Items item : items) &#123;</span><br><span class="line">		document = <span class="keyword">new</span> Document();</span><br><span class="line">		<span class="comment">/**</span></span><br><span class="line"><span class="comment">		 * 参数1:field的域名 参数2:要封装的数据 参数3:是否存储</span></span><br><span class="line"><span class="comment">		 */</span></span><br><span class="line">		Field name = <span class="keyword">new</span> TextField(<span class="string">&quot;name&quot;</span>, item.getName(), Store.YES);</span><br><span class="line">		Field id = <span class="keyword">new</span> StringField(<span class="string">&quot;id&quot;</span>, item.getId().toString(), Store.YES);</span><br><span class="line">		Field price = <span class="keyword">new</span> TextField(<span class="string">&quot;price&quot;</span>, item.getPrice().toString(), Store.YES);</span><br><span class="line">		<span class="comment">// 将field封装到document</span></span><br><span class="line">		document.add(name);</span><br><span class="line">		document.add(id);</span><br><span class="line">		document.add(price);</span><br><span class="line"></span><br><span class="line">		documents.add(document);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 创建一个标准分析器</span></span><br><span class="line">	Analyzer analyzer = <span class="keyword">new</span> StandardAnalyzer();</span><br><span class="line">	<span class="comment">// 索引库目录</span></span><br><span class="line">	Directory directory = FSDirectory.open(<span class="keyword">new</span> File(<span class="string">&quot;D:\\Repository\\indexDatabase\\test&quot;</span>));</span><br><span class="line">	<span class="comment">// 创建IndexWriterConfig</span></span><br><span class="line">	IndexWriterConfig indexWriterConfig = <span class="keyword">new</span> IndexWriterConfig(analyzer);</span><br><span class="line">	IndexWriter indexWriter = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="comment">// 创建IndexWriter</span></span><br><span class="line">		indexWriter = <span class="keyword">new</span> IndexWriter(directory, indexWriterConfig);</span><br><span class="line">		<span class="keyword">for</span> (Document doc : documents) &#123;</span><br><span class="line">			indexWriter.addDocument(doc);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">	&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">		<span class="comment">// 关闭IndexWriter</span></span><br><span class="line">		indexWriter.close();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="5-搜索索引"><a href="#5-搜索索引" class="headerlink" title="5. 搜索索引"></a>5. 搜索索引</h3><h4 id="使用QueryParse"><a href="#使用QueryParse" class="headerlink" title="使用QueryParse"></a>使用QueryParse</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">searchIndex</span><span class="params">()</span> <span class="keyword">throws</span> ParseException </span>&#123;</span><br><span class="line">	<span class="comment">// 创建标准分析器</span></span><br><span class="line">	Analyzer analyzer = <span class="keyword">new</span> StandardAnalyzer();</span><br><span class="line">	<span class="comment">// 创建QueryParser,c</span></span><br><span class="line">	<span class="comment">// 参数1:Field域名 参数2:分析器</span></span><br><span class="line">	QueryParser queryParser = <span class="keyword">new</span> QueryParser(<span class="string">&quot;name&quot;</span>, analyzer);</span><br><span class="line">	<span class="comment">// 创建Query 查找name为冰箱的</span></span><br><span class="line">	Query query = queryParser.parse(<span class="string">&quot;name:冰箱&quot;</span>);</span><br><span class="line">	<span class="comment">// 索引库目录</span></span><br><span class="line">	Directory directory = FSDirectory.open(<span class="keyword">new</span> File(<span class="string">&quot;D:\\Repository\\indexDatabase\\test&quot;</span>));</span><br><span class="line">	IndexReader indexReader = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="comment">// 创建IndexReader</span></span><br><span class="line">		indexReader = DirectoryReader.open(directory);</span><br><span class="line">		<span class="comment">// 创建IndexSearcher</span></span><br><span class="line">		IndexSearcher indexSearcher = <span class="keyword">new</span> IndexSearcher(indexReader);</span><br><span class="line">		<span class="comment">// 执行搜索,并返回TopDoc对象 参数1:query对象 参数2:最大记录数</span></span><br><span class="line">		TopDocs topDocs = indexSearcher.search(query, <span class="number">10</span>);</span><br><span class="line">		<span class="comment">// 获得TopDocs中的记录对象</span></span><br><span class="line">		ScoreDoc[] scoreDocs = topDocs.scoreDocs;</span><br><span class="line">		<span class="keyword">for</span> (ScoreDoc scoreDoc : scoreDocs) &#123;</span><br><span class="line">			<span class="comment">// 获得doc的ID</span></span><br><span class="line">			<span class="keyword">int</span> docId = scoreDoc.doc;</span><br><span class="line">			<span class="comment">// 根据id查找到doc</span></span><br><span class="line">			Document doc = indexSearcher.doc(docId);</span><br><span class="line">			<span class="comment">// 打印数据</span></span><br><span class="line">			System.out.println(<span class="string">&quot;商品名: &quot;</span> + doc.get(<span class="string">&quot;name&quot;</span>));</span><br><span class="line">			System.out.println(<span class="string">&quot;价格: &quot;</span> + doc.get(<span class="string">&quot;price&quot;</span>));</span><br><span class="line">		&#125;</span><br><span class="line">	&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">	&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">		<span class="comment">// 关闭reader</span></span><br><span class="line">		indexReader.close();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="使用Query的子类"><a href="#使用Query的子类" class="headerlink" title="使用Query的子类"></a>使用Query的子类</h4><p><strong>TermQuery</strong></p>
<p>TermQuery使用搜索关键词进行查询。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">searcher</span><span class="params">(Query query)</span> </span>&#123;</span><br><span class="line">	<span class="comment">// 索引库</span></span><br><span class="line">	Directory directory = FSDirectory.open(<span class="keyword">new</span> File(<span class="string">&quot;D:\\Repository\\indexDatabase\\test&quot;</span>));</span><br><span class="line">	<span class="comment">// IndexReader</span></span><br><span class="line">	IndexReader reader = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		reader = DirectoryReader.open(directory);</span><br><span class="line">		<span class="comment">// IndexSearcher</span></span><br><span class="line">		IndexSearcher searcher = <span class="keyword">new</span> IndexSearcher(reader);</span><br><span class="line">		TopDocs topDocs = searcher.search(query, <span class="number">10</span>);</span><br><span class="line">		ScoreDoc[] scoreDocs = topDocs.scoreDocs;</span><br><span class="line">		<span class="keyword">for</span> (ScoreDoc scoreDoc : scoreDocs) &#123;</span><br><span class="line">			<span class="keyword">int</span> docId = scoreDoc.doc;</span><br><span class="line">			Document document = searcher.doc(docId);</span><br><span class="line">			System.out.println(<span class="string">&quot;商品id :&quot;</span> + document.get(<span class="string">&quot;id&quot;</span>));</span><br><span class="line">			System.out.println(<span class="string">&quot;商品名称 :&quot;</span> + document.get(<span class="string">&quot;name&quot;</span>));</span><br><span class="line">			System.out.println(<span class="string">&quot;商品价格 :&quot;</span> + document.get(<span class="string">&quot;price&quot;</span>));</span><br><span class="line">		&#125;</span><br><span class="line">	&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">	&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">		reader.close();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">termQuery</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="comment">// 创建TermQuery 查询name中有冰箱的 等效于 name:冰箱</span></span><br><span class="line">	Query query = <span class="keyword">new</span> TermQuery(<span class="keyword">new</span> Term(<span class="string">&quot;name&quot;</span>, <span class="string">&quot;冰箱&quot;</span>));</span><br><span class="line">	searcher(query);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>NumericRangeQuery</strong></p>
<p>数字范围查询</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">numericRangeQuery</span><span class="params">()</span></span>&#123;</span><br><span class="line">	<span class="comment">// 创建查询</span></span><br><span class="line">	<span class="comment">// 第一个参数：域名</span></span><br><span class="line">	<span class="comment">// 第二个参数：最小值</span></span><br><span class="line">	<span class="comment">// 第三个参数：最大值</span></span><br><span class="line">	<span class="comment">// 第四个参数：是否包含最小值</span></span><br><span class="line">	<span class="comment">// 第五个参数：是否包含最大值</span></span><br><span class="line">	Query query = NumericRangeQuery.newLongRange(<span class="string">&quot;price&quot;</span>, l00, <span class="number">1000</span>, <span class="keyword">true</span>,<span class="keyword">true</span>);</span><br><span class="line">	<span class="comment">// 2、 执行搜索</span></span><br><span class="line">	searcher(query);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>BooleanQuery</strong></p>
<p>布尔查询,用于组合条件查询。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">   <span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">booleanQuery</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">	BooleanQuery query = <span class="keyword">new</span> BooleanQuery();</span><br><span class="line">	Query query1 = <span class="keyword">new</span> TermQuery(<span class="keyword">new</span> Term(<span class="string">&quot;id&quot;</span>, <span class="string">&quot;3&quot;</span>));</span><br><span class="line">	Query query2 = NumericRangeQuery.newFloatRange(<span class="string">&quot;price&quot;</span>, <span class="number">10f</span>, <span class="number">200f</span>,</span><br><span class="line">			<span class="keyword">true</span>, <span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//MUST：查询条件必须满足，相当于AND</span></span><br><span class="line">	<span class="comment">//SHOULD:查询条件可选，相当于OR</span></span><br><span class="line">	<span class="comment">//MUST_NOT：查询条件不能满足，相当于NOT非</span></span><br><span class="line">	query.add(query1, Occur.MUST);</span><br><span class="line">	query.add(query2, Occur.SHOULD);</span><br><span class="line">	</span><br><span class="line">	System.out.println(query);</span><br><span class="line"></span><br><span class="line">	searcher(query);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li>MUST和MUST表示“与”的关系，即“交集”。 </li>
<li>MUST和MUST_NOT前者包含后者不包含。</li>
<li>MUST_NOT和MUST_NOT没有结果,没有意义。</li>
<li>SHOULD与MUST表示MUST，SHOULD失去意义。</li>
<li>SHOUlD与MUST_NOT相当于MUST与MUST_NOT。</li>
<li>SHOULD与SHOULD表示“或”的概念。</li>
</ol>
<h3 id="6-删除索引"><a href="#6-删除索引" class="headerlink" title="6. 删除索引"></a>6. 删除索引</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteIndex</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="comment">// 指定索引库</span></span><br><span class="line">		Directory directory = FSDirectory.open(<span class="keyword">new</span> File(<span class="string">&quot;D:\\Repository\\indexDatabase\\test&quot;</span>));</span><br><span class="line">		<span class="comment">// 创建IndexWriterConfig</span></span><br><span class="line">		IndexWriterConfig indexWriterConfig = <span class="keyword">new</span> IndexWriterConfig(<span class="keyword">new</span> StandardAnalyzer());</span><br><span class="line">		<span class="comment">// 创建IndexWriter</span></span><br><span class="line">		IndexWriter indexWriter = <span class="keyword">new</span> IndexWriter(directory, indexWriterConfig);</span><br><span class="line">		<span class="comment">// 删除指定的索引</span></span><br><span class="line">		indexWriter.deleteDocuments(<span class="keyword">new</span> Term(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;冰箱&quot;</span>));</span><br><span class="line">		<span class="comment">// 关闭indexWriter</span></span><br><span class="line">		indexWriter.close();</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<h3 id="7-修改索引"><a href="#7-修改索引" class="headerlink" title="7. 修改索引"></a>7. 修改索引</h3><p>在Lucene中修改索引即是替换索引,先将原来的索引删除,再保存新的索引。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">modifyIndex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="comment">// 指定索引库</span></span><br><span class="line">	Directory directory = FSDirectory.open(<span class="keyword">new</span> File(<span class="string">&quot;D:\\Repository\\indexDatabase\\test&quot;</span>));</span><br><span class="line">	<span class="comment">// IndexWriterConfig</span></span><br><span class="line">	IndexWriterConfig indexWriterConfig = <span class="keyword">new</span> IndexWriterConfig(<span class="keyword">new</span> StandardAnalyzer());</span><br><span class="line">	<span class="comment">// IndexWriter</span></span><br><span class="line">	IndexWriter indexWriter = <span class="keyword">new</span> IndexWriter(directory, indexWriterConfig);</span><br><span class="line">	<span class="comment">// 创建一个Document</span></span><br><span class="line">	Document document = <span class="keyword">new</span> Document();</span><br><span class="line">	Field name = <span class="keyword">new</span> TextField(<span class="string">&quot;name&quot;</span>, <span class="string">&quot;比利海灵顿&quot;</span>, Store.YES);</span><br><span class="line">	document.add(name);</span><br><span class="line">	<span class="comment">// 修改索引</span></span><br><span class="line">	indexWriter.updateDocument(<span class="keyword">new</span> Term(<span class="string">&quot;name&quot;</span>, <span class="string">&quot;冰箱&quot;</span>), document);</span><br><span class="line">	indexWriter.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="8-相关度排序"><a href="#8-相关度排序" class="headerlink" title="8. 相关度排序"></a>8. 相关度排序</h3><p>Lucene通过计算Term的权重,对查询关键字和索引文档的相关度进行打分,分越高的就排在越前面。</p>
<p>影响Term的权重有两个因素:</p>
<ul>
<li>Term Frequency:Term在文档中的出现频率,次数越多,则代表这个Term对该文档越重要,即权重越高。</li>
<li>Document Frequency:指多少文档包含这个Term的频率,频率越高,则代表这个Term越不重要,即权重越低。</li>
</ul>
<h4 id="手动设置权值"><a href="#手动设置权值" class="headerlink" title="手动设置权值"></a>手动设置权值</h4><p><strong>在创建索引时设置权值</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">  <span class="keyword">for</span> (Items item : items) &#123;</span><br><span class="line">	document = <span class="keyword">new</span> Document();</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 参数1:field的域名 参数2:要封装的数据 参数3:是否存储</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	Field name = <span class="keyword">new</span> TextField(<span class="string">&quot;name&quot;</span>, item.getName(), Store.YES);</span><br><span class="line">	Field id = <span class="keyword">new</span> StringField(<span class="string">&quot;id&quot;</span>, item.getId().toString(), Store.YES);</span><br><span class="line">	Field price = <span class="keyword">new</span> TextField(<span class="string">&quot;price&quot;</span>, item.getPrice().toString(), Store.YES);</span><br><span class="line">	<span class="comment">// 给name域增加权值</span></span><br><span class="line">	name.setBoost(<span class="number">100f</span>);</span><br><span class="line">	<span class="comment">// 将field封装到document</span></span><br><span class="line">	document.add(name);</span><br><span class="line">	document.add(id);</span><br><span class="line">	document.add(price);</span><br><span class="line"></span><br><span class="line">	documents.add(document);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>在搜索时设置权值</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setBoosts</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">		<span class="comment">// 搜索的域名数组</span></span><br><span class="line">		String[] fields = &#123; <span class="string">&quot;name&quot;</span>, <span class="string">&quot;price&quot;</span> &#125;;</span><br><span class="line">		<span class="comment">// 设置权值</span></span><br><span class="line">		Map&lt;String, Float&gt; boosts = <span class="keyword">new</span> HashMap&lt;String, Float&gt;();</span><br><span class="line">		<span class="comment">// 给name域设置权重</span></span><br><span class="line">		boosts.put(<span class="string">&quot;name&quot;</span>, <span class="number">100f</span>);</span><br><span class="line">		<span class="comment">// 创建MultiFieldQueryParse</span></span><br><span class="line">		MultiFieldQueryParser multiFieldQueryParser = <span class="keyword">new</span> MultiFieldQueryParser(fields, <span class="keyword">new</span> StandardAnalyzer(), boosts);</span><br><span class="line">		<span class="comment">// 创建Query</span></span><br><span class="line">		Query query = multiFieldQueryParser.parse(<span class="string">&quot;冰箱&quot;</span>);</span><br><span class="line">		searcher(query);</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/yuwanzi.io/tags/%E5%85%A8%E6%96%87%E6%A3%80%E7%B4%A2%E5%BC%95%E6%93%8E/" rel="tag"># 全文检索引擎</a>
              <a href="/yuwanzi.io/tags/Lucene/" rel="tag"># Lucene</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2016/06/17/2016-06-17-springmvc-02/" rel="prev" title="Spring MVC进阶应用">
                  <i class="fa fa-chevron-left"></i> Spring MVC进阶应用
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2016/06/24/2016-06-24-nginx-initiation/" rel="next" title="如何安装与搭建一个Nginx服务器">
                  如何安装与搭建一个Nginx服务器 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">玉丸子</span>
</div>
  <div class="powered-by">Erstellt mit  <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/yuwanzi.io/js/utils.js"></script><script src="/yuwanzi.io/js/motion.js"></script><script src="/yuwanzi.io/js/schemes/muse.js"></script><script src="/yuwanzi.io/js/next-boot.js"></script>

  






  





</body>
</html>
